/*
Copyright  2018 Blockchain Technology and Application Joint Lab, Fintech Research Center of ISCAS.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
 */
import React, {Component, PropTypes} from 'react';
import {createContainer} from 'meteor/react-meteor-data';
import {browserHistory} from 'react-router';

import {X509} from 'jsrsasign';
import {List, ListItem} from 'material-ui/List';
import {Users} from "../api/users/users";

import Divider from 'material-ui/Divider';
import Dialog from 'material-ui/Dialog';
import Subheader from 'material-ui/Subheader';
import {blue400, grey400, red700, green700} from 'material-ui/styles/colors';
import SvgIconErr from 'material-ui/svg-icons/alert/error';
import SvgIconCheck from 'material-ui/svg-icons/toggle/check-box';
import Snackbar from 'material-ui/Snackbar';
import Chip from 'material-ui/Chip';
import IconMenu from 'material-ui/IconMenu';
import MenuItem from 'material-ui/MenuItem';
import IconButton from 'material-ui/IconButton';
import TextField from 'material-ui/TextField';
import FlatButton from 'material-ui/FlatButton';
import MoreVertIcon from 'material-ui/svg-icons/navigation/more-vert';
import Avatar from 'material-ui/Avatar';
import Drawer from 'material-ui/Drawer';
import AppBar from 'material-ui/AppBar';
import NavigationLeft from 'material-ui/svg-icons/hardware/keyboard-arrow-left';
import InfiniteScroll from 'react-infinite-scroller';

import ReplaceUserCert from './RepchainUserRegister';
import {RegisterUser} from '../api/register_user/register_user'
import repchain from '../api/repchainUtil'
import moment from "moment/moment";

const styles = {
    footer: {
        position: 'fixed',
        bottom: 0,
        width: '100%',
    },
    root: {
        flexWrap: 'wrap',
        justifyContent: 'space-around',
    },
    itemList: {
        width: '100%',
        height: '100%',
        overflowY: 'auto',
    },
    toolbar: {
        position: 'fixed',
        top: 0,
        width: '100%',
    },
}


const iconButtonElement = (
    <IconButton
        touch={true}
        tooltip='more'
        tooltipPosition='bottom-left'
    >
        <MoreVertIcon color={grey400}/>
    </IconButton>
);


export default class RegisterUsers extends Component {
    constructor(props) {
        super(props);
        this.state = {
            open: false,
            user_item: '',

            import_cert_open: false,
            update_user:{},
            repchainDestroyUserinfo: '',
            repchainDestroyUserTxid: '',
            snackbar_open: false,

            checkPass: false,
            confirmDestroy: false,
            user_pass: '',
            pass_err: '',
            destroy_user_address: '',

            pageNum: 10,
            query: null,
            page: 0,
            userItems: [],
            hasMore: true,

        };
    }

    componentWillUnmount(){
        this._isMounted = false;
    }
    componentWillMount(){
        this._isMounted = true;
        if (Session.get('curUser') === 'none'){
            browserHistory.push('/login');
        }
    }
    loadmore(page) {
        let pageNum = this.state.pageNum;
        let offset = pageNum * (page - 1)
        Meteor.subscribe('registerUsers',{}, pageNum, offset);
        setTimeout(function () {
            offset = this.state.userItems.length;
            let res=RegisterUser.find({},{sort: { createdAt: -1 }, limit:pageNum, skip:offset }).fetch()
            console.log("res：" + res.length)

            if(res.length < pageNum){
                this.setStateByCheck({userItems:this.state.userItems.concat(res),hasMore:false})
                return;
            }else{
                this.setStateByCheck({userItems:this.state.userItems.concat(res), hasMore:true})
            }

        }.bind(this), 100)
    }

    componentDidMount(x, y, z) {
        this.setState({cw: window.innerWidth, ch: window.innerHeight});
    }

    handleClose() {
        this.setState({open: false});
    }

    setStateByCheck(po){
        if(this._isMounted){
            this.setState(po);
        }
    }

    handleChange(status) {
        const {import_cert_open} = this.state;
        this.setState({import_cert_open: status})
    }

    renderItems() {
        const {open, user_item, import_cert_open, update_user,repchainDestroyUserinfo, checkPass, destroy_user_address, repchainDestroyUserTxid, snackbar_open} = this.state;
        let res = [];
        this.state.userItems.map((item) => {
            if (!item.isAdmin && item.status)
                res.push(
                    <div
                        key={item.account_address}
                    >
                        <ListItem
                            leftAvatar={<Avatar src={item.avatar}/>}
                            rightIconButton={<IconMenu
                                iconButtonElement={iconButtonElement}>
                                <MenuItem
                                    onClick={(e) => {
                                        this.setState({open: !open, user_item: item})
                                    }}
                                > 详细信息</MenuItem>
                                <MenuItem
                                    onClick={(e) => {
                                        this.setState({import_cert_open: !import_cert_open, update_user:item})
                                    }}
                                > 证书替换</MenuItem>
                                <MenuItem
                                    onClick={(e) => {
                                        this.setState({checkPass: true, destroy_user_address: item.account_address});
                                    }}
                                > 账户注销</MenuItem>
                            </IconMenu>}
                            primaryText={item.name}
                            onClick={(event) => {
                            }}
                            primaryTogglesNestedList={true}
                            nestedItems={[
                                <ListItem key={1} primaryText={'手机: ' + item.phone}/>,
                                <ListItem key={2} primaryText={'邮箱: ' + item.email}/>,
                                <ListItem key={3} primaryText={'账户地址: ' + item.account_address}/>,
                                <ListItem key={4} primaryText={'工作单位: ' + item.unit}/>,
                                <ListItem key={5} primaryText={'通讯地址: ' + item.address}/>,
                            ]}
                        />
                        <Divider inset={true}/>
                    </div>
                );
        });
        return res;
    }

    renderImportUserCert() {
        return <ReplaceUserCert registerUser={false} user_item={this.state.update_user} handleChange={status => this.handleChange(status)}/>
    }

    renderUserInfo() {
        const {open, user_item} = this.state;
        let userInfo;
        const cert = new X509();
        try {
            cert.readCertPEM(user_item.user_certificate_pem);
        } catch (e) {
            console.log(e);
            throw Error("用户证书有错！");
        }
        return (
            <Drawer width={this.state.open ? this.state.cw : 0}
                    containerStyle={{position: 'fixed', top: 0, overflowY: 'hidden'}}
                    openSecondary={true}
                    open={this.state.open}
            >
                <div style={{height: this.state.ch, overflowY: 'auto', wordWrap: 'break-word'}}>
                    <AppBar title='用户详细信息'
                            style={styles.toolbar}
                            iconElementLeft={
                                <IconButton
                                    onTouchTap={() => {
                                        this.setState({open: !open})
                                    }
                                    }
                                    iconStyle={{width: 48, height: 48}}
                                    style={{padding: 0}}
                                >
                                    <NavigationLeft/>
                                </IconButton>
                            }>
                    </AppBar>
                    <List style={{margin: 15}}>
                        <Subheader style={{marginTop: 80, textAlign: 'center'}}>用户基本信息</Subheader>
                        <ListItem primaryText={'姓名: ' + user_item.name}/>
                        <ListItem primaryText={'手机: ' + user_item.phone}/>
                        <ListItem primaryText={'邮箱: ' + user_item.email}/>
                        <ListItem primaryText={'工作单位: ' + user_item.unit}/>
                        <ListItem primaryText={'通讯地址: ' + user_item.address}/>
                        <ListItem primaryText={'日期: ' + moment(cert.getNotBefore().toString(),'YYYYMMDDhhmmssZ').format('YYYY-MM-DD HH:mm:ss Z')}/>
                    </List>
                    <List style={{margin: 15}}>
                        <Subheader style={{textAlign: 'center'}}>证书信息</Subheader>
                        <ListItem primaryText={'序列号: ' + cert.getSerialNumberHex()}/>
                        <ListItem primaryText={'签名算法: ' + cert.getSignatureAlgorithmName()}/>
                        <ListItem primaryText={'有效期至: ' + moment(cert.getNotAfter().toString(),'YYYYMMDDhhmmssZ').format('YYYY-MM-DD HH:mm:ss Z')}/>
                        <ListItem primaryText={'签名信息: ' + cert.getSignatureValueHex()}/>
                    </List>
                </div>
            </Drawer>
        )
    }

    renderChip() {
        let avatar_color = this.state.repchainDestroyUserTxid == '' ? red700 : green700;
        let avatar_icon = this.state.repchainDestroyUserTxid == '' ? <SvgIconErr/> : <SvgIconCheck/>;
        const {snackbar_open} = this.state;
        return (
            <Chip style={{top: 25,}} onClick={() => {
                this.setState({snackbar_open: false});
            }}>
                <Avatar color={avatar_color} icon={avatar_icon}/>
                {this.state.repchainDestroyUserinfo}
            </Chip>
        );
    }

    render() {
        const {open, user_item, import_cert_open, snackbar_open, checkPass, repchainDestroyUserTxid, repchainDestroyUserinfo, destroy_user_address, confirmDestroy, user_pass, pass_err} = this.state;
        const actionDestroy = [
            <FlatButton
                label="确认"
                primary={confirmDestroy}
                disabled={!confirmDestroy}
                onClick={(event) => {
                    repchain.destroyUser(destroy_user_address, user_pass, Session.get('curUser').prv_key_pem_encrypted, Session.get('curUser').account_address, (err, result) => {
                        if (err) {
                            if(err.message.indexOf("不存在") > -1)
                                this.setState({repchainDestroyUserinfo: '不存在该证书!'});
                            else
                                this.setState({repchainDestroyUserinfo: err.message});
                            console.log(err);
                        } else {
                            this.setState({repchainDestroyUserinfo: "注销请求已提交，请等待确认！", repchainDestroyUserTxid: result});
                            console.log(result);
                        }
                        this.setState({snackbar_open: true, checkPass: false});
                    });
                }}
            />,
            <FlatButton
                label="取消"
                primary={true}
                keyboardFocused={true}
                onClick={() => this.setState({checkPass: false})}
            />,
        ];
        return (
            <div style={styles.root}>
                <List style={styles.itemList}>
                    <Subheader> 用户列表</Subheader>
                    <InfiniteScroll
                        pageStart={this.state.page}
                        loadMore={this.loadmore.bind(this)}
                        hasMore={this.state.hasMore}
                        loader={<div className='loader'>Loading...</div>}
                    >
                        {this.renderItems()}
                    </InfiniteScroll>
                </List>
                {import_cert_open ? this.renderImportUserCert() : null}
                {open ? this.renderUserInfo() : null}
                <Snackbar
                    open={this.state.snackbar_open}
                    message={this.renderChip()}
                    autoHideDuration={3000}
                    bodyStyle={{backgroundColor: 'rgba(47,47,47,0.7)', height: 'auto', textAlign: 'center'}}
                    contentStyle={{height: 80, display: 'inline-block'}}
                    onRequestClose={(reason) => {
                        this.setState({snackbar_open: !snackbar_open});
                    }}
                />
                <Dialog
                    title="注销用户提醒"
                    actions={actionDestroy}
                    modal={false}
                    open={checkPass}
                    onRequestClose={() => {
                        this.setState({checkPass: false})
                    }}
                >
                    <Divider style={{border: '1px dashed', marginTop: 2}}/>
                        请注意:<br/>
                        1. 请再次确认是否注销用户。<br/>
                        2. 注销用户，会导致该用户的后续操作不可用。
                    <Divider style={{border: '1px dashed', marginBottom: 30}}/>
                    <p style={{color: red700}}>*输入私钥密码:</p>
                    <TextField
                        type='password'
                        floatingLabelText='私钥密码'
                        floatingLabelStyle={{color: blue400}}
                        errorText={pass_err}
                        hintText='输入密码'
                        onChange={(e, newValue) => {
                            if (newValue === '')
                                this.setState({confirmDestroy: false, user_pass: newValue, pass_err: '密码不可为空'});
                            else
                                this.setState({confirmDestroy: true, user_pass: newValue, pass_err: ''});
                        }}
                    />
                </Dialog>
            </div>
        )
    }
}

